# -*- coding: utf-8 -*-
"""
Created on Sat Feb 20 18:42:13 2021
this code is modified from mnist_cnn for detecting cat and dog
@author: LI
"""


from time import sleep
import tensorflow as tf
from tensorflow.python.platform import gfile   #gfile.FastGFile()
import os, sys, time
import matplotlib.pyplot as plt
import numpy as np
import glob
from skimage import io, transform
import cv2 as cv

from imageReady import generateDataSet,_show_time,  showLoss, shuffleDatas


import config as cfg
#载入数据集
config = cfg.Config()
row =  config.row
col = config.col
c = config.c

#plot,ax = plt.subplots(1,1)
with tf.Session(graph = tf.Graph())as sess:
    save_path = "./model"
    #tf.saved_model.loader.load(sess,[tf.saved_model.tag_constants.TRAINING],save_path)
    sess.run(tf.global_variables_initializer())         #加了这句话就会导致图初始化
    
    
    if 1:
        # 加载模型  ckpt
        saver = tf.train.import_meta_graph(save_path + '/model.ckpt.meta')  # 先加载meta文件，具体到文件名
        saver.restore(sess, tf.train.latest_checkpoint(save_path))  # 加载检查点文件checkpoint，具体到文件夹即可
        graph = tf.get_default_graph()  # 绘制tensorflow图
        input_x = sess.graph.get_tensor_by_name('x-input:0')
        input_y = sess.graph.get_tensor_by_name('y-input:0')
        keep_prob = sess.graph.get_tensor_by_name('keep_prob:0')
        output = sess.graph.get_tensor_by_name('output:0')
        version_cnn = sess.graph.get_tensor_by_name('version:0')
    else:
        #加载模型 pb
        print("###load pb model###")
        sleep(1)
        model_pb = os.path.abspath('./model_pb/')
        with gfile.FastGFile(model_pb + '/model.pb', 'rb') as f:
            graph_def = tf.GraphDef()
            graph_def.ParseFromString(f.read())
            sess.graph.as_default()
            tf.import_graph_def(graph_def, name='') # 导入计算图
                
            if 0:
                graph = tf.get_default_graph()
                for op in graph.get_operations():
                    print(op.name)
                    time.sleep(1)

            input_x = sess.graph.get_tensor_by_name('x-input:0')
            input_y = sess.graph.get_tensor_by_name('y-input:0')
            keep_prob = sess.graph.get_tensor_by_name('keep_prob:0')
            output = sess.graph.get_tensor_by_name('output:0')
            version_cnn = sess.graph.get_tensor_by_name('version:0')

    print(input_x)
    print(input_y)
    print("model version: ", version_cnn.eval())
    sleep(1)

    #test
    imgs_test, labels_test = generateDataSet("/home/user/ljl/cnn/valid", row, col)
    imgs_test, labels_test = shuffleDatas(imgs_test, labels_test)
    
    length = imgs_test.shape[0]
    errorNum = 0
    start_time = time.time()
    for idx in range(length):
        simpleList = []
        simpleList_label = []
        simpleList.append(imgs_test[idx])
        simpleList_label.append(labels_test[idx])
        
        img_in = np.asarray(simpleList)
        label_in = np.asarray(simpleList_label)
        print(img_in.shape)

        
        prediction = sess.run(output, feed_dict={input_x:img_in, input_y:label_in, keep_prob:1.0 })
        pre_idx = np.argmax(prediction)
        if pre_idx == 0: 
            print(list(label_in[0]))
            if [1, 0] != list(label_in[0]):
                errorNum += 1
        else:
            if [0,1] != list(label_in[0]):
                errorNum += 1
        print('Training Accuracy=' , prediction)
        print(' -> output class is: ', pre_idx, '-> prediction   is: ', prediction[0][pre_idx])
        print("label is: ", label_in[0])
        #sleep(1)
    print(imgs_test.shape)
    print("errorNUm: ", errorNum, "  length: ", (length),  "  ", errorNum/(length))

    #end_time = time.clock()
    cost_time = time.time() - start_time
    h, m, s = _show_time(cost_time)


    print('>>>>>>>>>>>>>>>\t end \t<<<<<<<<<<<<<')